<template>
	<div :class="prefixCls">
		<template v-for="(action, index) in getActions" :key="index">
			<Popconfirm v-if="action.popConfirm" v-bind="action.pop">
				<Button v-bind="action.btn">
					<BasicIcon v-if="action.icon" :icon="action.icon" />
					{{ action.title }}
				</Button>
			</Popconfirm>
			<Button v-bind="action.btn" v-else>
				<BasicIcon v-if="action.icon" :icon="action.icon" />{{ action.title }}
			</Button>
			<Divider type="vertical" v-if="divider && index < actions.length - 1"></Divider>
		</template>
	</div>
</template>
<script lang="ts">
import { computed, defineComponent, PropType, toRaw } from 'vue';
import { Button, Popconfirm, Divider } from 'ant-design-vue';
import BasicIcon from '#/Icon/src/BasicIcon.vue';
import { ActionItem } from '../types/tableAction';
import { isBoolean, isFunction } from '@/utils/is';
import { useDesign } from '@/hooks/web/useDesign';
import { omit } from 'lodash-es';

export default defineComponent({
	name: 'TableAction',
	components: { BasicIcon, Button, Popconfirm, Divider },
	props: {
		actions: { type: Array as PropType<ActionItem[]>, default: null },
		divider: { type: Boolean, default: false },
	},
	setup(props) {
		const { prefixCls } = useDesign('basic-table-action');
		function ifIsShow(action: ActionItem): boolean {
			let ifShow = action.ifShow;
			let rs = true;
			if (isBoolean(ifShow)) {
				rs = ifShow;
			}
			if (isFunction(ifShow)) {
				rs = ifShow();
			}
			return rs;
		}

		const getActions = computed(() => {
			return (toRaw(props.actions) || [])
				.filter(action => {
					return ifIsShow(action);
				})
				.map(action => {
					const { popConfirm } = action;

					if (popConfirm) {
						return {
							btn: {
								type: action.type || 'link',
								size: action.size || 'small',
								disabled: action.disabled || false,
								...omit(action.btnProps, ['type', 'size', 'disabled']),
							},
							pop: {
								...(popConfirm || {}),
								title: popConfirm.title || '确定删除?',
								okText: popConfirm?.okText || '确定',
								cancelText: popConfirm?.cancelText || '取消',
								onConfirm: popConfirm?.confirm,
								onCancel: popConfirm?.cancel,
							},
							...action,
						};
					}
					return {
						btn: {
							type: action.type || 'link',
							size: action.size || 'small',
							href: action.href,
							onClick: action?.onClick,
							disabled: action.disabled || false,
							...omit(action.btnProps, ['type', 'size', 'disabled', 'href', 'onClick']),
						},
						pop: null,
						...action,
					};
				});
		});

		return {
			prefixCls,
			getActions,
		};
	},
});
</script>
<style lang="less">
@prefix-cls: ~'@{namespace}-basic-table-action';

.@{prefix-cls} {
	display: inline-flex;
	align-items: center;
	.ant-divider-vertical {
		margin: 0 3px;
	}
}
</style>
